<?php

namespace pc\controllers;
use common\models\Sitemap;
use Yii;
use yii\web\Response;

class SitemapController extends BaseController
{
    public function behaviors(){
        return parent::behaviors();
    }
    /*
     * 前期蜘蛛量的问题，优先推送栏目页面、聚合页面、标签页面，美女列表页面手动组合部分连接提交
     */
    public function actionIndex(){
        $type = (int)Yii::$app->request->get('type');
        $typeXmlName = [1 => 'menuUrls' , 2 => 'tagUrls' , 3 => 'starUrls' , 4 => 'portrayUrls' , 5 => 'newsUrls'];

        if(!in_array($type,array_keys($typeXmlName))){
            exit('参数错误');
        }

        $maxId = (int)Yii::$app->request->get('mid');

        $data = [];
        switch ($type){
            case 1 : $data = Sitemap::menuUrls(); break;
            case 2 : $data = Sitemap::tagUrls(); break;
            case 3 : $data = Sitemap::starUrls(); break;
            case 4 : $data = Sitemap::portrayUrls(); break;
            case 5 : $data = Sitemap::newsUrls($maxId); break;
        }

        !empty($data) && $this->createXml($typeXmlName[$type],$data);
    }


    private function createXml($xmlName,$data = []){
        $response = Yii::$app->response;
        $response->format = Response::FORMAT_XML;
        $response->charset = Yii::$app->charset;

        $filePath = Yii::getAlias('@pc')."/web/{$xmlName}.xml";

        $response->formatters = [
            $response->format => [
                'class' => 'yii\web\XmlResponseFormatter',
                'rootTag' => 'urlset', //根节点
                'itemTag' => 'url', //单元
            ]
        ];

        $response->data = $data;

        ob_start();
        $response->send();
        $content = ob_get_contents();
        $content = str_ireplace('<urlset>','<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',$content);
        $fp = fopen($filePath, "w");
        fwrite($fp, $content);
        fclose($fp);
        ob_end_flush();
    }



}
